import axios from 'axios'
// import Nprogress from 'nprogress'
import { message } from 'antd'

// 请求头附带token
const http = axios.create({
  baseURL: 'http://localhost:7001',
  timeout: 3000,
  headers: { authorization: localStorage.getItem('token') },
})

// 添加请求拦截器
http.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    console.log('config', config)
    //开启加载条
    // Nprogress.start()
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
http.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    if (response.data.statu === 401) {
      console.log(111)
      // 未登录 跳转登录页面
      window.location.href = '/login'
      localStorage.clear()
      message.warning(response.data.msg)
    } else if (response.data.statu === 403) {
      // 无权限 友好提示
      message.warning(response.data.msg)
    }
    //关闭加载条
    // Nprogress.done()
    return response
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error)
  },
)

// axios方法封装
const httpGet = async (url: string, data: object) => {
  const res = await http.get(url, { params: data })
  return res
}
const httpPost = async (url: string, data: object) => {
  const res = await http.post(url, data)
  return res
}
const httpDel = async (url: string, data: object) => {
  const res = await http.delete(url, { params: data })
  return res
}
const httpPut = async (url: string, data: object) => {
  const res = await http.put(url, { params: data })
  return res
}

export { httpGet, httpPost, httpDel, httpPut }
